<?php
namespace app\common\lib;
class GatewayCurl {
    private $client = null;
    private $host = ['127.0.0.1'];
    private $port = 7777;
    private $gateway = 1;
    
    public function __construct($gateway = 1) {
        $this->gateway = $gateway;
        $this->client = curl_init();
        curl_setopt($this->client,CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($this->client, CURLOPT_POST, 1); //设置为POST方式
        curl_setopt($this->client, CURLOPT_RETURNTRANSFER, true);
        
    }
    
    public function send($url, $data) {
        /* var_dump($data);
        return [
            'success' => true,
            'body' => ''
        ]; */
        if(is_array($data)) {
            $data = json_encode($data);
        }
        
        curl_setopt($this->client, CURLOPT_URL, 'http://' . $this->host[$this->gateway - 1] . ':' . $this->port . '/sendGateway/' . $url);
        curl_setopt($this->client, CURLOPT_POSTFIELDS, $data);//POST数据
        $repResult = [
            'success' => false,
            'body' => ''
        ];
        
        $body = curl_exec($this->client);
        curl_close($this->client);
        $repResult['body'] = $body;
        
        try {
            $result = json_decode($body, true);
            if($result !== null){
                if(isset($result['statuscode']) && $result['statuscode'] == 200){
                    $repResult['success'] = true;
                }
            }
        } catch (\Exception $e) {
            
        }
        
        return $repResult;
        
        
    }
}